﻿using SchoolCommunicationSystem.Models;
using SCS.Business;
using SCS.Common.Models;
using System.Linq;
using System.Web.Mvc;

namespace SchoolCommunicationSystem.Controllers
{
    public class AccountManagementController : Controller
    {
        MembershipService _membershipServices = new MembershipService();
        // MembershipRoleServices _membershipRoleServices = new MembershipRoleServices();
        TeacherServices _teacherServices = new TeacherServices();
        //ParentServices _parentServices = new ParentServices();
        Parent2Services _parent2Services = new Parent2Services();
        //
        // GET: /AccountManagement/

        /// <summary>
        /// Index
        /// </summary>
        /// <returns>View</returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// get and search admin account
        /// </summary>
        /// <param name="searchString">string</param>
        /// <returns>view</returns>
        public ActionResult AdminAccount(string searchString = "")
        {
            var model = new ListAdminModel
            {
                AdminList = _membershipServices.SearchAdminUser(searchString)
            };
            return View(model);
        }

        /// <summary>
        /// get all teacher account
        /// </summary>
        /// <param name="searchString">string</param>
        /// <returns>view</returns>
        public ActionResult TeacherAccount(string searchString = "")
        {
            var model = new ListTeacherAddViewModel
            {
                TeacherList = _membershipServices.SearchTeacherUser(searchString)
            };
            return View(model);
        }

        /// <summary>
        /// pre update teacher account
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>view</returns>
        public ActionResult UpdateTeacherAccount(int id)
        {
            if (Request.IsAjaxRequest())
            {
                var subjectName = _teacherServices.GetAllSubject().Select(t => new SelectListItem()
                {
                    Text = t.subjectName,
                    Value = t.subjectID.ToString(),
                }).ToList();
                ListTeacherUpdateViewModel ListTeacherUpdateViewModels = new ListTeacherUpdateViewModel();
                MembershipUser _membershipUser = _membershipServices.GetTeacherAccountByID(id);
                ListTeacherUpdateViewModels.TeacherRole = _membershipUser.MembershipRoles.FirstOrDefault().roleID;
                ListTeacherUpdateViewModels.TeacherMembershipUser = _membershipUser;
                ListTeacherUpdateViewModels.TeacherUserID = _membershipUser.userID;
                ListTeacherUpdateViewModels.SubjectSelectList = subjectName;
                if (ListTeacherUpdateViewModels.TeacherRole == 4)
                {
                    ListTeacherUpdateViewModels._subjectID = (byte?)_membershipUser.Teachers.FirstOrDefault().Subject.subjectID;
                }
                return View("UpdateTeacherAccount", ListTeacherUpdateViewModels);
            }
            else

                return View();
        }

        /// <summary>
        /// update teacher account information
        /// </summary>
        /// <param name="membershipUser">MembershipUser</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult UpdateTeacherAccount(ListTeacherUpdateViewModel ListTeacherUpdateViewModels)
        {
            if (ModelState.IsValid)
            {

                MembershipUser membershipUser = _membershipServices.GetTeacherAccountByID(ListTeacherUpdateViewModels.TeacherMembershipUser.userID);
                membershipUser.userName = ListTeacherUpdateViewModels.TeacherMembershipUser.userName;
                membershipUser.email = ListTeacherUpdateViewModels.TeacherMembershipUser.email;
                membershipUser.isLockedOut = ListTeacherUpdateViewModels.TeacherMembershipUser.isLockedOut;
                membershipUser = _membershipServices.SetRoleForTeacher(membershipUser, ListTeacherUpdateViewModels.TeacherRole);
                if (ListTeacherUpdateViewModels.TeacherRole == 3)
                {
                    membershipUser.Teachers.FirstOrDefault().subjectID = null;
                }
                else
                {
                    membershipUser.Teachers.FirstOrDefault().subjectID = ListTeacherUpdateViewModels._subjectID;
                }
                _membershipServices.UpdateTeacherAccount(membershipUser);

                TempData["Msg"] = "Đã sửa thông tin tài khoản giáo viên thành công";
                return RedirectToAction("TeacherAccount");
            }

            return View(ListTeacherUpdateViewModels);
        }

        /// <summary>
        /// get all parent account
        /// </summary>
        /// <param name="searchString">string</param>
        /// <returns>view</returns>
        public ActionResult ParentsAccount(string searchString = "")
        {
            var model = new ListParentsAddViewModel
            {
                ParentsList = _membershipServices.SearchParentsUser(searchString)
            };

            return View(model);
        }

        /// <summary>
        /// pre update parent account
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdateParentAccount(int id)
        {
            if (Request.IsAjaxRequest())
            {
                MembershipUser _membershipUser = _membershipServices.GetParentAccountByID(id);

                return View("UpdateParentAccount", _membershipUser);
            }
            else

                return View();
        }

        /// <summary>
        /// update parent account information
        /// </summary>
        /// <param name="membershipUser">MembershipUser</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult UpdateParentAccount(MembershipUser membershipUser)
        {
            if (ModelState.IsValid)
            {
                _membershipServices.UpdateParentAccount(membershipUser);

                TempData["Msg"] = "Đã sửa thông tin tài khoản phụ huynh thành công";
                return RedirectToAction("ParentsAccount");
            }

            return View(membershipUser);
        }

        /// <summary>
        /// Pre create account admin
        /// </summary>
        /// <returns>View</returns>
        public ActionResult CreateAccountAdmin()
        {
            var viewModel = new AdminAddViewModel
            {
                UserName = string.Empty,
                Email = string.Empty,
                Password = string.Empty
            };

            // See if a return url is present or not and add it
            var returnUrl = Request["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                viewModel.ReturnUrl = returnUrl;
            }

            return View(viewModel);
        }

        /// <summary>
        /// Create account admin
        /// </summary>
        /// <param name="adminAddViewModel">AdminAddViewModel</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult CreateAccountAdmin(AdminAddViewModel adminAddViewModel)
        {
            if (ModelState.IsValid)
            {
                var userToSave = new MembershipUser
                {
                    userName = adminAddViewModel.UserName,
                    email = adminAddViewModel.Email,
                    password = adminAddViewModel.Password
                };
                userToSave.userID = _membershipServices.GetMemberID();
                var createStatus = _membershipServices.CreateUser(userToSave, 1);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, "[Tên đăng nhập] hoặc [Email] đã tồn tại");
                    return View(adminAddViewModel);
                }
                return RedirectToAction("AdminAccount", "AccountManagement");
            }

            return View(adminAddViewModel);
        }

        /// <summary>
        /// Pre create account teacher
        /// </summary>
        /// <returns>View</returns>
        public ActionResult CreateAccountTeacher()
        {
            var teacherName = _teacherServices.GetAllTeacherNoUserID().Select(t => new SelectListItem()
            {
                Text = t.teacherName,
                Value = t.teacherID.ToString(),
            }).ToList();

            var subjectName = _teacherServices.GetAllSubject().Select(t => new SelectListItem()
            {
                Text = t.subjectName,
                Value = t.subjectID.ToString(),
            }).ToList();

            var viewModel = new TeacherAddViewModel
            {
                TeacherSelectList = teacherName,
                SubjectSelectList = subjectName,
                UserName = string.Empty,
                Email = string.Empty,
                Password = string.Empty
            };

            // See if a return url is present or not and add it
            var returnUrl = Request["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                viewModel.ReturnUrl = returnUrl;
            }

            return View(viewModel);
        }
        
        /// <summary>
        /// Create account teacher
        /// </summary>
        /// <param name="userModel">TeacherAddViewModel</param>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult CreateAccountTeacher(TeacherAddViewModel userModel)
        {
            if (ModelState.IsValid)
            {
                var userToSave = new MembershipUser
                {
                    userName = userModel.UserName,
                    email = userModel.Email,
                    password = userModel.Password
                };
                int teacherID = userModel._teacherID;
                userToSave.userID = _membershipServices.GetMemberID();

                if (userModel.isLeaderTeacher == false)
                {
                    var createStatus = _membershipServices.CreateUser(userToSave, 3);
                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError(string.Empty, "[Tên đăng nhập] hoặc [Email] đã tồn tại");
                        var teacherNameList = _teacherServices.GetAllTeacherNoUserID().Select(t => new SelectListItem()
                        {
                            Text = t.teacherName,
                            Value = t.teacherID.ToString(),
                        }).ToList();
                        userModel.TeacherSelectList = teacherNameList;
                        var subjectNameList = _teacherServices.GetAllSubject().Select(t => new SelectListItem()
                        {
                            Text = t.subjectName,
                            Value = t.subjectID.ToString(),
                        }).ToList();
                        userModel.TeacherSelectList = teacherNameList;
                        userModel.SubjectSelectList = subjectNameList;

                        return View(userModel);
                    }
                    else
                    {
                        Teacher teacherToUpdate = _teacherServices.GetTeacher(teacherID);
                        teacherToUpdate.userID = userToSave.userID;
                        _teacherServices.UpdateTeacher(teacherToUpdate);
                    }
                }
                else
                {
                    var createStatus = _membershipServices.CreateUser(userToSave, 4);
                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError(string.Empty, "[Tên đăng nhập] hoặc [Email] đã tồn tại");
                        var teacherNameList = _teacherServices.GetAllTeacherNoUserID().Select(t => new SelectListItem()
                        {
                            Text = t.teacherName,
                            Value = t.teacherID.ToString(),
                        }).ToList();
                        var subjectNameList = _teacherServices.GetAllSubject().Select(t => new SelectListItem()
                        {
                            Text = t.subjectName,
                            Value = t.subjectID.ToString(),
                        }).ToList();
                        userModel.TeacherSelectList = teacherNameList;
                        userModel.SubjectSelectList = subjectNameList;

                        return View(userModel);
                    }
                    else
                    {
                        Teacher teacherToUpdate = _teacherServices.GetTeacher(teacherID);
                        teacherToUpdate.userID = userToSave.userID;
                        teacherToUpdate.subjectID = userModel._subjectID;
                        _teacherServices.UpdateTeacher(teacherToUpdate);

                    }
                }

                return RedirectToAction("TeacherAccount", "AccountManagement");
            }

            var teacherName = _teacherServices.GetAllTeacherNoUserID().Select(t => new SelectListItem()
            {
                Text = t.teacherName,
                Value = t.teacherID.ToString(),
            }).ToList();
            var subjectName = _teacherServices.GetAllSubject().Select(t => new SelectListItem()
            {
                Text = t.subjectName,
                Value = t.subjectID.ToString(),
            }).ToList();
            userModel.TeacherSelectList = teacherName;
            userModel.SubjectSelectList = subjectName;

            return View(userModel);
        }
    }
}
